import { useState, useCallback, useEffect } from 'react';
import { Edit, Trash2, X } from 'lucide-react';
import { useTemplate } from '@/contexts/template';
import type { CheckItemTemplate, CheckItemType } from '@/types/template';

type PreviewStepProps = {
  onNext: () => void;
  onBack: () => void;
};

export function PreviewStep({ onNext, onBack }: PreviewStepProps) {
  const { state, updateTemplateItems, setDefaultMaturityLevel } = useTemplate();
  const items = state.currentTemplate?.items || [];
  
  // 只有评估类型为105（数据安全评估）时才显示成熟度等级
  const showMaturityLevel = state.currentTemplate?.assessment_type === '105';

  // 成熟度等级选择对话框状态
  const [showMaturityDialog, setShowMaturityDialog] = useState(false);
  const [selectedDefaultMaturityLevel, setSelectedDefaultMaturityLevel] = useState(1);

  // Pagination state
  const pageSizeOptions = [10, 20, 30] as const;
  const [itemsPerPage, setItemsPerPage] = useState<typeof pageSizeOptions[number]>(10);
  const [currentPage, setCurrentPage] = useState(1);
  const totalPages = Math.max(1, Math.ceil(items.length / itemsPerPage));

  // Ensure current page is valid when items change
  useEffect(() => {
    // 如果当前页超过总页数则调整
    setCurrentPage(prev => (prev > totalPages ? totalPages : prev));
  }, [totalPages]);

  // 当页码或分页大小变化时重新计算可视数据
  useEffect(() => {
    setCurrentPage(1); // 改变每页数量后回到第一页
  }, [itemsPerPage]);

  // Items to render on current page
  const paginatedItems = items.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  const [editingItem, setEditingItem] = useState<CheckItemTemplate | null>(null);
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    guide: '',
    compliance_type: 'risk' as CheckItemType,
    maturity_level: 1
  });

  const handleAddItem = useCallback((e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.title.trim()) return;
    
    const newItem: CheckItemTemplate = {
      id: `item-${Date.now()}`,
      title: formData.title.trim(),
      description: formData.description.trim(),
      guide: formData.guide.trim(),
      compliance_type: formData.compliance_type,
      ...(showMaturityLevel && { maturity_level: formData.maturity_level || 1 }),
    };
    
    const updatedItems = [...items, newItem];
    updateTemplateItems(updatedItems);
    
    // Reset form
    setFormData({
      title: '',
      description: '',
      guide: '',
      compliance_type: 'risk' as CheckItemType,
      maturity_level: 1
    });
  }, [formData, items, updateTemplateItems, showMaturityLevel]);

  const handleEdit = (id: string) => {
    const itemToEdit = items.find(item => item.id === id);
    if (itemToEdit) {
      setEditingItem(itemToEdit);
      setFormData({
        title: itemToEdit.title,
        description: itemToEdit.description || '',
        guide: itemToEdit.guide || '',
        compliance_type: itemToEdit.compliance_type,
        maturity_level: itemToEdit.maturity_level || 1
      });
    }
  };

  const handleSaveEdit = useCallback((e: React.FormEvent) => {
    e.preventDefault();
    if (!editingItem) return;
    
    const updatedItems = items.map(item => 
      item.id === editingItem.id 
        ? { 
            ...item, 
            title: formData.title.trim(),
            description: formData.description.trim(),
            guide: formData.guide.trim(),
            compliance_type: formData.compliance_type,
            ...(showMaturityLevel && { maturity_level: formData.maturity_level || 1 })
          }
        : item
    );
    
    updateTemplateItems(updatedItems);
    setEditingItem(null);
  }, [editingItem, formData, items, updateTemplateItems, showMaturityLevel]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target as HTMLInputElement;
    setFormData(prev => ({ 
      ...prev, 
      [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : value 
    }));
  };

  const handleDelete = useCallback((id: string) => {
    if (window.confirm('确定要删除这个检查项吗？')) {
      const updatedItems = items.filter(item => item.id !== id);
      updateTemplateItems(updatedItems);
    }
  }, [items, updateTemplateItems]);

  const getTypeBadge = (type: CheckItemType) => (
    <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
      type === 'risk' ? 'bg-red-100 text-red-800' : 'bg-blue-100 text-blue-800'
    }`}>
      {type === 'risk' ? '风险项' : '保障项'}
    </span>
  );


  const truncateText = (text: string, maxLength: number) => {
    if (!text) return '';
    return text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;
  };

  // 处理下一步按钮点击
  const handleNextClick = () => {
    if (showMaturityLevel) {
      // 如果是数据安全评估，显示成熟度等级选择对话框
      setShowMaturityDialog(true);
    } else {
      // 其他评估类型直接进入下一步
      onNext();
    }
  };

  // 确认成熟度等级并进入下一步
  const handleConfirmMaturityLevel = () => {
    setShowMaturityDialog(false);
    // 将选择的默认成熟度等级保存到context中
    setDefaultMaturityLevel(selectedDefaultMaturityLevel);
    // 继续到下一步
    onNext();
  };

  return (
    <div className="space-y-6">
      <div className="space-y-6">
        <div className="space-y-2">
          <h3 className="text-lg font-medium text-slate-900">添加新检查项</h3>
          <p className="text-sm text-slate-500">
            添加新的检查项到模板中
          </p>
        </div>

        <form onSubmit={handleAddItem} className="space-y-4 rounded-lg border p-4">
          <div className={`grid grid-cols-1 gap-4 ${showMaturityLevel ? 'sm:grid-cols-3' : 'sm:grid-cols-2'}`}>
            <div>
              <label htmlFor="new-title" className="mb-1 block text-sm font-medium text-gray-700">
                标题 <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                id="new-title"
                name="title"
                value={formData.title}
                onChange={handleInputChange}
                className="w-full rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                placeholder="输入检查项标题"
                required
              />
            </div>
            
            <div>
              <label htmlFor="new-compliance-type" className="mb-1 block text-sm font-medium text-gray-700">
                类型 <span className="text-red-500">*</span>
              </label>
              <select
                id="new-compliance-type"
                name="compliance_type"
                value={formData.compliance_type}
                onChange={handleInputChange}
                className="w-full rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                required
              >
                <option value="risk">风险项</option>
                <option value="guarantee">保障项</option>
              </select>
            </div>

            {showMaturityLevel && (
              <div>
                <label htmlFor="new-maturity-level" className="mb-1 block text-sm font-medium text-gray-700">
                  成熟度等级 <span className="text-red-500">*</span>
                </label>
                <select
                  id="new-maturity-level"
                  name="maturity_level"
                  value={formData.maturity_level}
                  onChange={handleInputChange}
                  className="w-full rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                  required
                >
                  <option value={1}>1级</option>
                  <option value={2}>2级</option>
                  <option value={3}>3级</option>
                  <option value={4}>4级</option>
                  <option value={5}>5级</option>
                </select>
              </div>
            )}
          </div>
          
          <div>
            <label htmlFor="new-description" className="mb-1 block text-sm font-medium text-gray-700">
              描述
            </label>
            <textarea
              id="new-description"
              name="description"
              value={formData.description}
              onChange={handleInputChange}
              rows={2}
              className="w-full rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              placeholder="输入检查项详细描述"
            />
          </div>
          
          <div>
            <label htmlFor="new-guidance" className="mb-1 block text-sm font-medium text-gray-700">
              指引
            </label>
            <textarea
              id="new-guide"
              name="guide"
              value={formData.guide}
              onChange={handleInputChange}
              rows={2}
              className="w-full rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              placeholder="输入检查项指引说明"
            />
          </div>
          
          <div className="flex justify-end">
            <button
              type="submit"
              disabled={!formData.title.trim()}
              className={`rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 ${
                !formData.title.trim() ? 'cursor-not-allowed opacity-50' : ''
              }`}
            >
              添加检查项
            </button>
          </div>
        </form>
      </div>

      <div className="space-y-2">
        <h3 className="text-lg font-medium text-slate-900">预览检查项</h3>
        <p className="text-sm text-slate-500">
          请检查导入的检查项信息，您可以进行编辑或删除操作
        </p>
      </div>

      <div className="rounded-md border">
        <div className="relative w-full overflow-auto">
          <table className="w-full caption-bottom text-sm">
            <thead className="[&_tr]:border-b">
              <tr className="border-b transition-colors hover:bg-slate-50/50">
                <th className="h-12 px-4 text-left align-middle font-medium text-slate-500 [&:has([role=checkbox])]:pr-0">
                  标题
                </th>
                <th className="h-12 px-4 text-left align-middle font-medium text-slate-500 [&:has([role=checkbox])]:pr-0">
                  描述
                </th>
                <th className="h-12 px-4 text-left align-middle font-medium text-slate-500 [&:has([role=checkbox])]:pr-0">
                  指引
                </th>
                <th className="h-12 px-4 text-left align-middle font-medium text-slate-500 [&:has([role=checkbox])]:pr-0">
                  类型
                </th>
                {showMaturityLevel && (
                  <th className="h-12 px-4 text-center align-middle font-medium text-slate-500 [&:has([role=checkbox])]:pr-0">
                    成熟度等级
                  </th>
                )}
                <th className="h-12 px-4 text-right align-middle font-medium text-slate-500 [&:has([role=checkbox])]:pr-0">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="[&_tr:last-child]:border-0">
              {items.length > 0 ? (
                paginatedItems.map((item) => (
                  <tr key={item.id} className="border-b transition-colors hover:bg-slate-50">
                    <td className="p-4 align-middle font-medium">
                      <div className="flex flex-col">
                        <span>{item.title}</span>
                      </div>
                    </td>
                    <td className="p-4 align-middle">
                      <div className="max-w-[300px] truncate" title={item.description}>
                        {truncateText(item.description || '', 50)}
                      </div>
                    </td>
                    <td className="p-4 align-middle">
                      <div className="max-w-[300px] truncate" title={item.guide}>
                        {truncateText(item.guide || '', 50)}
                      </div>
                    </td>
                    <td className="p-4 align-middle">
                      {getTypeBadge(item.compliance_type)}
                    </td>
                    {showMaturityLevel && (
                      <td className="p-4 align-middle text-center">
                        <span className="inline-flex items-center rounded-full bg-slate-100 px-2.5 py-0.5 text-xs font-medium text-slate-800">
                          {item.maturity_level || 1}级
                        </span>
                      </td>
                    )}
                    <td className="p-4 align-middle text-right">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          type="button"
                          onClick={() => handleEdit(item.id)}
                          className="inline-flex h-8 w-8 items-center justify-center rounded-md text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                          aria-label="编辑"
                        >
                          <Edit className="h-4 w-4" />
                          <span className="sr-only">编辑</span>
                        </button>
                        <button
                          type="button"
                          onClick={() => handleDelete(item.id)}
                          className="inline-flex h-9 w-9 items-center justify-center whitespace-nowrap rounded-md border border-red-200 bg-white text-sm font-medium text-red-500 shadow-sm transition-colors hover:bg-red-50 hover:text-red-700 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-red-500 disabled:pointer-events-none disabled:opacity-50"
                          aria-label="删除"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={showMaturityLevel ? 6 : 5} className="h-24 p-4 text-center text-slate-500">
                    没有可预览的检查项
                  </td>
                </tr>
              )}
            </tbody>
          </table>

          {/* Pagination Controls */}
          {items.length > 0 && (
            <div className="flex flex-col items-end gap-2 px-4 py-3 sm:flex-row sm:items-center sm:justify-end">
              {/* Page size selector */}
              <div className="flex items-center gap-1 text-sm text-slate-700">
                <span>每页显示</span>
                <select
                  value={itemsPerPage}
                  onChange={e => setItemsPerPage(Number(e.target.value) as typeof pageSizeOptions[number])}
                  className="rounded-md border border-slate-300 bg-white px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-primary-600"
                  aria-label="选择每页展示数量"
                >
                  {pageSizeOptions.map(size => (
                    <option key={size} value={size}>{size}</option>
                  ))}
                </select>
              </div>

              <button
                type="button"
                onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                disabled={currentPage === 1}
                className="inline-flex items-center justify-center whitespace-nowrap rounded-md border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium shadow-sm transition-colors hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-950 disabled:pointer-events-none disabled:opacity-50"
                aria-label="上一页"
              >
                上一页
              </button>
              <span className="text-sm text-slate-700" aria-label={`当前页 ${currentPage} / 总页数 ${totalPages}`}>
                {currentPage}/{totalPages}
              </span>
              <button
                type="button"
                onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                disabled={currentPage === totalPages}
                className="inline-flex items-center justify-center whitespace-nowrap rounded-md border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium shadow-sm transition-colors hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-950 disabled:pointer-events-none disabled:opacity-50"
                aria-label="下一页"
              >
                下一页
              </button>
            </div>
          )}
        </div>
      </div>

      <div className="flex items-center justify-between pt-4">
        <button
          type="button"
          onClick={onBack}
          className="inline-flex items-center justify-center whitespace-nowrap rounded-md border border-slate-200 bg-white px-4 py-2 text-sm font-medium shadow-sm transition-colors hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-950 disabled:pointer-events-none disabled:opacity-50"
        >
          上一步
        </button>
        <div className="space-x-3">
          <button
            type="button"
            onClick={() => window.history.back()}
            className="inline-flex items-center justify-center whitespace-nowrap rounded-md border border-slate-200 bg-white px-4 py-2 text-sm font-medium shadow-sm transition-colors hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-950 disabled:pointer-events-none disabled:opacity-50"
          >
            取消
          </button>
          <button
            type="button"
            onClick={handleNextClick}
            disabled={items.length === 0}
            className={`inline-flex items-center justify-center whitespace-nowrap rounded-md bg-primary-600 px-4 py-2 text-sm font-medium shadow transition-colors hover:bg-primary-600/90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-950 disabled:pointer-events-none disabled:opacity-50 ${items.length === 0 ? 'opacity-50' : ''}`}
          >
            下一步
          </button>
        </div>
      </div>

      {/* Edit Dialog */}
      {editingItem && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="relative w-full max-w-md rounded-lg bg-white p-6 shadow-lg">
            <div className="mb-4 flex items-center justify-between">
              <h3 className="text-lg font-medium">编辑检查项</h3>
              <button
                type="button"
                onClick={() => setEditingItem(null)}
                className="rounded-md p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-500"
                aria-label="关闭"
              >
                <X className="h-5 w-5" />
              </button>
            </div>
            
            <form onSubmit={handleSaveEdit} className="space-y-4">
              <div>
                <label htmlFor="title" className="mb-1 block text-sm font-medium text-gray-700">
                  标题 <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  id="title"
                  name="title"
                  value={formData.title}
                  onChange={handleInputChange}
                  className="w-full rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                  placeholder="输入检查项标题"
                  required
                />
              </div>
              
              <div>
                <label htmlFor="description" className="mb-1 block text-sm font-medium text-gray-700">
                  描述
                </label>
                <textarea
                  id="description"
                  name="description"
                  value={formData.description}
                  onChange={handleInputChange}
                  rows={4}
                  className="w-full rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                  placeholder="输入检查项详细描述"
                />
              </div>
              
              <div>
                <label htmlFor="guidance" className="mb-1 block text-sm font-medium text-gray-700">
                  指引
                </label>
                <textarea
                  id="guide"
                  name="guide"
                  value={formData.guide}
                  onChange={handleInputChange}
                  rows={4}
                  className="w-full rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                  placeholder="输入检查项指引说明"
                />
              </div>
              
              <div>
                <label htmlFor="compliance-type" className="mb-1 block text-sm font-medium text-gray-700">
                  类型 <span className="text-red-500">*</span>
                </label>
                <select
                  id="compliance-type"
                  name="compliance_type"
                  value={formData.compliance_type}
                  onChange={handleInputChange}
                  className="w-full rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                  required
                >
                  <option value="risk">风险项</option>
                  <option value="guarantee">保障项</option>
                </select>
              </div>

              {showMaturityLevel && (
                <div>
                  <label htmlFor="maturity-level" className="mb-1 block text-sm font-medium text-gray-700">
                    成熟度等级 <span className="text-red-500">*</span>
                  </label>
                  <select
                    id="maturity-level"
                    name="maturity_level"
                    value={formData.maturity_level}
                    onChange={handleInputChange}
                    className="w-full rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                    required
                  >
                    <option value={1}>1级</option>
                    <option value={2}>2级</option>
                    <option value={3}>3级</option>
                    <option value={4}>4级</option>
                    <option value={5}>5级</option>
                  </select>
                </div>
              )}
              
              <div className="flex justify-end space-x-3 pt-2">
                <button
                  type="button"
                  onClick={() => setEditingItem(null)}
                  className="rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
                >
                  取消
                </button>
                <button
                  type="submit"
                  disabled={!formData.title.trim()}
                  className={`rounded-md px-4 py-2 text-sm font-medium text-white shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 ${
                    !formData.title.trim() 
                      ? 'cursor-not-allowed bg-gray-400' 
                      : 'bg-blue-600 hover:bg-blue-700'
                  }`}
                >
                  保存更改
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* 成熟度等级选择对话框（仅数据安全评估） */}
      {showMaturityDialog && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="relative w-full max-w-md rounded-lg bg-white p-6 shadow-lg">
            <div className="mb-4">
              <h3 className="text-lg font-medium text-slate-900">选择默认成熟度等级</h3>
              <p className="mt-2 text-sm text-slate-500">
                请为当前模板选择默认的成熟度等级，该等级将作为创建评估计划时的默认值。
              </p>
            </div>
            
            <div className="mb-6">
              <label htmlFor="default-maturity-level" className="mb-2 block text-sm font-medium text-gray-700">
                默认成熟度等级 <span className="text-red-500">*</span>
              </label>
              <select
                id="default-maturity-level"
                value={selectedDefaultMaturityLevel}
                onChange={(e) => setSelectedDefaultMaturityLevel(Number(e.target.value))}
                className="w-full rounded-md border border-gray-300 bg-white px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              >
                <option value={1}>等级 1</option>
                <option value={2}>等级 2</option>
                <option value={3}>等级 3</option>
                <option value={4}>等级 4</option>
                <option value={5}>等级 5</option>
              </select>
              <p className="mt-2 text-xs text-slate-500">
                成熟度等级范围：1（初始级）到 5（优化级）
              </p>
            </div>
            
            <div className="flex justify-end space-x-3">
              <button
                type="button"
                onClick={() => setShowMaturityDialog(false)}
                className="rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
              >
                取消
              </button>
              <button
                type="button"
                onClick={handleConfirmMaturityLevel}
                className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
              >
                确认并继续
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
